#coding: utf-8
class CulturalHeritage::CollectionsController < ApplicationController
  #before_filter :authenticate_user!

#Id del rol | Rol | Usuarios de ejemplo | Contraseña
#1 |	Miembro de institución cultural |	minstitucion	pukara
#2 |	Administrador del sistema |	asistema	pukara
#3 |	Miembro de la comunidad científica cultural |	mcomunidad pukara
#4 |	Miembro del INC |	minc	pukara
#5 |	Miembro de FFAA |	mffaa	pukara

  @@edit_roles = [2 , 4]
  def self.edit_roles
    @@edit_roles
  end

  @@multivalue = [["Todos","todos"],["Nombre","name"], ["Descripción","description"], ["Propietario","owner"], ["Institución Cultural","cultural_institution"]]
  def self.multivalue
    @@multivalue
  end

  @@my_notice = ""
  def self.my_notice
    @@my_notice
  end
  
  # GET /cultural_heritage/collections
  # GET /cultural_heritage/collections.xml
  def index
    @title_view = 'Colecciones'    

    @cultural_heritage_collections = CulturalHeritage::Collection.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @cultural_heritage_collections }
      format.json  { render :json => @cultural_heritage_collections }
    end
  end

  # GET /cultural_heritage/collections/1
  # GET /cultural_heritage/collections/1.xml
  def show
    @title_view = 'Colecciones'


    @cultural_heritage_collection = CulturalHeritage::Collection.find(params[:id])

#    @cultural_heritage_collection.cultural_heritages.each do |cultural_heritage|
#      cultural_heritage.photo
#    end


    @cultural_heritage_collection_photos = @cultural_heritage_collection.list_photos

#    holder = Dining.all # Takes all Dining records returned as an array and sets them to holder variable
#    holder << Shop.all # Pushes the Shop records array into the holder with the dining records
#    holder.flatten!# Next we flatten the array so we only have a single array.
#    winbledom
#    # Then we use the map method to run the given code one time for each instance
#    # in the holder array to extract the info we need. The results for every instance
#    # in holder are returned in an array which we then convert to_json.
#    @json = holder.map{|h| {lng: h.longitude, lat: h.latitude, class: h.class.to_s}}.to_json

    #@json = @cultural_heritage_collection.cultural_heritages.to_gmaps4rails do |cultural_heritage, marker|
    @json = "["

    @cultural_heritage_collection.cultural_heritages.each do |heritage|

      if (heritage.gmaps == true) or (heritage.obj_culturalInstitution.gmaps == true)
        if (heritage.gmaps == true)
          if !(@json.eql?("["))
            @json = @json  << ", "
          end
          @json = @json <<  '{"description":"'+define_info_window_for_search(heritage)+
                            '","title":'+'"'+heritage.name+
                            '","sidebar":"<fieldset id=\"agrupacion\" class=\"markers_item\" ><h3>'+
                            ((heritage.name.to_s.size > 35) ? heritage.name.to_s.slice(0,35)+" (...)" : heritage.name)+'</h3>'+'<p>'+
                            ((heritage.description.to_s.size > 115) ? heritage.description.to_s.slice(0,115)+" (...)" : heritage.description)+
                            '</p></fieldset>'+
                            '","lat":"'+heritage.latitude.to_s+'","lng":"'+heritage.longitude.to_s+
                            '","id":"'+heritage.name+'"}'
        else
          if (heritage.obj_culturalInstitution.gmaps == true)
            if !(@json.eql?("["))
              @json = @json  << ", "
            end
            @json = @json <<  '{"description":"'+define_info_window_for_search(heritage)+
                              '","title":'+'"'+heritage.name+
                              '","sidebar":"<fieldset id=\"agrupacion\" class=\"markers_item\" ><h3>'+
                              ((heritage.name.to_s.size >= 35) ? heritage.name.to_s.slice(0,35)+" (...)" : heritage.name)+'</h3>'+'<p>'+
                              ((heritage.description.to_s.size >= 115) ? heritage.description.to_s.slice(0,115)+" (...)" : heritage.description)+
                              '</p></fieldset>'+
                              '","lat":"'+heritage.obj_culturalInstitution.latitude.to_s+
                              '","lng":"'+ heritage.obj_culturalInstitution.longitude.to_s+'"}'
          end
        end
      end
    end

    @json = @json << "]"

#    @json = @cultural_heritage_collection.cultural_heritages.to_gmaps4rails do |cultural_heritage, marker|
#      marker.infowindow  cultural_heritage.define_info_window_for_marker_for_maps(root_url)
#      marker.title   cultural_heritage.name
#      marker.sidebar "Ubicacion"
#
#    end
    
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @cultural_heritage_collection }
    end
  end

  def define_info_window_for_search(parameter)
    if (parameter.list_avatars.length == 0) or (parameter.avatar_file_name.blank?)
      image = root_url << "images/pukara_logo.png"
    else
      if ! parameter.avatar_file_name.blank?
        image = parameter.avatar.url
      else
        image = parameter.list_avatars.at(0).avatar.url
      end
    end
    if parameter.group == 1
      referencia = "<div><h2><a href = '/cultural_heritage/cultural_heritages/"
      institucion = "<h3><a href = '/cultural_heritage/cultural_institutions/"+
                    parameter.obj_culturalInstitution.id.to_s+"'>"+
                    parameter.obj_culturalInstitution.name.to_s+"</a></h3>"
      mensaje = "<p>Patrimonio ubicado en: <h3>" + institucion+ "</h3></p>"
    else
      referencia = "<div><h2><a href = '/cultural_heritage/cultural_heritage_properties/"
      mensaje = ""
    end
    return  referencia+parameter.id.to_s+"'>"+parameter.name.to_s+"</a></h2><p>"+mensaje+"</p>"+
            "<p>"+parameter.description.to_s+"</p><img src="+image+
            "  style='thumb'/></div>"
  end


  # GET /cultural_heritage/collections/new
  # GET /cultural_heritage/collections/new.xml
  def new
    if (!user_signed_in? or !(@@edit_roles.include?(current_user.role)) )
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
      return
    end
    @title_view = 'Colecciones'
    @cultural_heritage_collection = CulturalHeritage::Collection.new

    @owners = Security::Person.all
    @states = CulturalHeritage::CollectionState.all
    @cultural_institutions = CulturalHeritage::CulturalInstitution.all

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @cultural_heritage_collection }
    end
  end

  # GET /cultural_heritage/collections/1/edit
  def edit
    if (!user_signed_in? or !(@@edit_roles.include?(current_user.role)) )
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
      return
    end
    
    @title_view = 'Colecciones'
    @cultural_heritage_collection = CulturalHeritage::Collection.find(params[:id])

    @owners = Security::Person.all
    @states = CulturalHeritage::CollectionState.all
    @cultural_institutions = CulturalHeritage::CulturalInstitution.all

    @states_heritage = CulturalHeritage::State.all
    @groups = CulturalHeritage::Group.all
    @subgroups = CulturalHeritage::SubGroup.all
    @cultural_heritage_cultural_heritages = []#CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["(cultural_heritage_cultural_heritages.collection IS NULL or cultural_heritage_cultural_heritages.collection = ?) and cultural_heritage_cultural_heritages.id != ?",@cultural_heritage_cultural_heritage.id,@cultural_heritage_cultural_heritage.id])
    @assignments_list = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["cultural_heritage_cultural_heritages.collection = ?",@cultural_heritage_collection.id])
  end

  # POST /cultural_heritage/collections
  # POST /cultural_heritage/collections.xml
  def create
    if (!user_signed_in? or !(@@edit_roles.include?(current_user.role)) )
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
      return
    end

    @cultural_heritage_collection = CulturalHeritage::Collection.new(params[:cultural_heritage_collection])

    @owners = Security::Person.all
    @states = CulturalHeritage::CollectionState.all
    @cultural_institutions = CulturalHeritage::CulturalInstitution.all

    respond_to do |format|
      if @cultural_heritage_collection.save
        #format.html { redirect_to(@cultural_heritage_collection, :notice => 'La colección fue creada satisfactoriamente.') }
        format.html { redirect_to(:controller=>"/cultural_heritage/collections",:action => 'assing',:id =>@cultural_heritage_collection.id, :notice => 'Agregue los miembros de la colección.') }
        format.xml  { render :xml => @cultural_heritage_collection, :status => :created, :location => @cultural_heritage_collection }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @cultural_heritage_collection.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /cultural_heritage/collections/1
  # PUT /cultural_heritage/collections/1.xml
  def update
    if (!user_signed_in? or !(@@edit_roles.include?(current_user.role)) )
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
      return
    end

    @cultural_heritage_collection = CulturalHeritage::Collection.find(params[:id])

    @owners = Security::Person.all
    @states = CulturalHeritage::CollectionState.all
    @cultural_institutions = CulturalHeritage::CulturalInstitution.all

#    @collection_photos = params[:photos]
#    @datos_s = @collection_photos.to_s

#    @collection_photos.each do |photo|
#      uploaded_io = photo#params[:cultural_heritage_collection_photo][:photo]
#      File.open(Rails.root.join('public', 'system', 'photos', uploaded_io.original_filename), 'wb') do |file|
#        file.write(uploaded_io.read)
#      end
#    end

#    @datos_s = $_FILES['collection_photos']['name'][0]

#    if @collection_photos.size > 0
#      @collection_photos.each do |photo|
#         @cultural_heritage_collection_photo =
#           CulturalHeritage::CollectionPhoto.new(
#             [
#               :collection => @cultural_heritage_collection.id,
#               :title => photo,
#               :description => "--",
#               :photo_file_name => photo
#             ]
#           )
#
#      end
#    end


    respond_to do |format|
      if @cultural_heritage_collection.update_attributes(params[:cultural_heritage_collection])
        format.html { redirect_to(@cultural_heritage_collection, :notice => 'La colección fue actualizada satisfactoriamente.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @cultural_heritage_collection.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /cultural_heritage/collections/1
  # DELETE /cultural_heritage/collections/1.xml
  def destroy
    if (!user_signed_in? or !(@@edit_roles.include?(current_user.role)) )
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
      return
    end

    @cultural_heritage_collection = CulturalHeritage::Collection.find(params[:id])

#    @cultural_heritages = @cultural_heritage_collection.cultural_heritages
#
#    @cultural_heritages.each do |cultural_heritages|
#        cultural_heritages.collection = nil
#        cultural_heritages.save
#    end

    @notice_destroy = ""
    if @cultural_heritage_collection.cultural_heritages.length == 0
      @cultural_heritage_collection.deleted = 1
      @cultural_heritage_collection.save

      @notice_destroy = "Colección eliminada."
    else
      @notice_destroy = "No es posible eliminar una colección que no esté vacía."
    end

    respond_to do |format|
      format.html { redirect_to(cultural_heritage_collections_url, :flash=>{:notice => @notice_destroy}) }
      format.xml  { head :ok }
    end
  end

  #tabla de búsqueda del index
  def update_table
    @search_text = params[:search_text].to_s
    @search_multivalue = params[:search_multivalue].to_s

    @cultural_heritage_collections = nil

    #Ahora busco dicho texto en los campos ed tipo string de Collections
    if ! @search_text.blank?
      case @search_multivalue
        when "todos" then          
          @cultural_heritage_collections =
            CulturalHeritage::Collection.find(
              :all,
              :joins=>[
                :obj_owner,
                'LEFT OUTER JOIN `cultural_heritage_cultural_institutions` ON `cultural_heritage_cultural_institutions`.`id` = `cultural_heritage_collections`.`cultural_institution`',
                :obj_collection_state
              ],
              :conditions=> [
                "cultural_heritage_collections.name LIKE ? OR " +
                "cultural_heritage_collections.description LIKE ? OR " +
                "cultural_heritage_collection_states.name LIKE ? OR " +
                "security_people.name LIKE ? OR " +
                "security_people.lastname LIKE ? OR " +
                "cultural_heritage_cultural_institutions.name LIKE ? OR " +
                "cultural_heritage_cultural_institutions.description LIKE ? ",
                "%"+@search_text+"%","%"+@search_text+"%",
                "%"+@search_text+"%",
                "%"+@search_text+"%","%"+@search_text+"%",
                "%"+@search_text+"%","%"+@search_text+"%"
              ]
            )
        when "name" then
          @cultural_heritage_collections =
            CulturalHeritage::Collection.find(
              :all,
              :conditions=> ["cultural_heritage_collections.name LIKE ? ","%"+@search_text+"%"]
            )
        when "description" then
          @cultural_heritage_collections =
            CulturalHeritage::Collection.find(
              :all,
              :conditions=> ["cultural_heritage_collections.description LIKE ? ","%"+@search_text+"%"]
            )
        when "state" then
          @cultural_heritage_collections =
            CulturalHeritage::Collection.find(
              :all,
              :joins=>:obj_collection_state,
              :conditions=> ["cultural_heritage_collection_states.name LIKE ? ","%"+@search_text+"%"]
            )
        when "owner" then
          @cultural_heritage_collections =
            CulturalHeritage::Collection.find(
              :all,
              :joins=>:obj_owner,
              :conditions=> [
                "security_people.name LIKE ? OR " +
                "security_people.lastname LIKE ? ",
                "%"+@search_text+"%","%"+@search_text+"%"
              ]
            )
        when "cultural_institution" then
          @cultural_heritage_collections =
            CulturalHeritage::Collection.find(
              :all,
              :joins=>'LEFT OUTER JOIN `cultural_heritage_cultural_institutions` ON `cultural_heritage_cultural_institutions`.`id` = `cultural_heritage_collections`.`cultural_institution`',
              :conditions=> [
                "cultural_heritage_cultural_institutions.name LIKE ? OR " +
                "cultural_heritage_cultural_institutions.description LIKE ? ",
                "%"+@search_text+"%","%"+@search_text+"%"
              ]
            )
        
      end
      
    else
      @cultural_heritage_collections = CulturalHeritage::Collection.all
    end

    render :partial => "table"
  end

    #Primero obtengo los id de los Owners
#    @owners =
#      Security::Person.find(
#        :all,
#        :conditions=>["security_people.name LIKE ? or security_people.lastname LIKE ?", "%"+@search_text.to_s+"%", "%"+@search_text.to_s+"%"]
#      );

    #Ahora de las Instituciones culturales :: OJO, eliminar cultural description cuando la carga sea muy alta
#    @cultural_institutions =
#      CulturalHeritage::CulturalInstitution.find(
#        :all,
#        :conditions=>["cultural_heritage_cultural_institutions.name LIKE ? or cultural_heritage_cultural_institutions.description LIKE ?", "%"+@search_text.to_s+"%", "%"+@search_text.to_s+"%"]
#      );


#      CulturalHeritage::Collection.find(
#              :all,
#              :joins=>[],
#              :conditions=>
#                [ "cultural_heritage_collections.id = ? or cultural_heritage_collections.name LIKE ? OR " +
#                  "cultural_heritage_collections.description LIKE ? OR " +
#                  "cultural_heritage_collections.owner in (?) OR " +
#                  "cultural_heritage_collections.cultural_institution in (?) ",
#                  @search_text,
#                  "%"+@search_text.to_s+"%",
#                  "%"+@search_text.to_s+"%",
#                  (@owners.empty? ? '' : @owners.map(&:id)),
#                  (@cultural_institutions.empty? ? '' : @cultural_institutions.map(&:id)) ]
#              )
#      end

  #Funciones para la asignación
  #Index de la asignación
  def assing
    if (!user_signed_in? or !(@@edit_roles.include?(current_user.role)) )
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
      return
    end

    @title_view = 'Colecciones'

    @cultural_heritage_collection = CulturalHeritage::Collection.find(params[:id])

    @cultural_institutions = CulturalHeritage::CulturalInstitution.all
    @states_heritage = CulturalHeritage::State.all
    @groups = CulturalHeritage::Group.all
    @subgroups = CulturalHeritage::SubGroup.all
    @cultural_heritage_cultural_heritages = []#CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["(cultural_heritage_cultural_heritages.collection IS NULL or cultural_heritage_cultural_heritages.collection = ?) and cultural_heritage_cultural_heritages.id != ?",@cultural_heritage_cultural_heritage.id,@cultural_heritage_cultural_heritage.id])
    @assignments_list = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["cultural_heritage_cultural_heritages.collection = ?",@cultural_heritage_collection.id])
  end

  #actualizar tabla de asignación
  def update_assing_table
    @search_name = params[:search_name]
    @cultural_institution = params[:cultural_institution][:id]
    #@start_date = params[:calendar][:start_date]
    #@end_date = params[:calendar][:end_date]
    @search_state = params[:search_state]
    @search_group = params[:search_group]
    @search_subgroup = params[:search_subgroup]
    @cultural_heritage_id = params[:cultural_heritage_id]
    my_heritage_conditions  = String.new
    my_heritage_values      = Array.new
    my_heritage_conditions << "(cultural_heritage_cultural_heritages.collection IS NULL) "
    #my_heritage_conditions << "AND cultural_heritage_cultural_heritages.id != ? "
    #my_heritage_values.push(@cultural_heritage_id)

    if (! @search_name.blank?)
      my_heritage_conditions << "AND (cultural_heritage_cultural_heritages.name LIKE ? or cultural_heritage_cultural_heritages.description LIKE ? or cultural_heritage_cultural_heritages.materials LIKE ? or cultural_heritage_cultural_heritages.nationalRegistrationCode LIKE ?) "
      my_heritage_values.push('%'+@search_name+'%')
      my_heritage_values.push('%'+@search_name+'%')
      my_heritage_values.push('%'+@search_name+'%')
      my_heritage_values.push('%'+@search_name+'%')
    end

    if (!@cultural_institution.blank?)
      my_heritage_conditions << "AND (cultural_heritage_cultural_heritages.typeCulturalInstitution = 1 and cultural_heritage_cultural_heritages.culturalInstitution = ?) "
      my_heritage_values.push(@cultural_institution)
    end

#    if (! @start_date.blank?)
#        my_heritage_conditions << " AND (cultural_heritage_cultural_heritages.created_at >= ?) "
#        my_heritage_values.push(@start_date.to_date)
#    end
#
#    if (!@end_date.blank?)
#        my_heritage_conditions << " AND (cultural_heritage_cultural_heritages.created_at <= ?) "
#        my_heritage_values.push(@end_date.to_date)
#    end

    if (!@search_state.blank?)
        my_heritage_conditions << " AND (cultural_heritage_cultural_heritages.state = ?) "
        my_heritage_values.push(@search_state)
    end

    #if (!@search_group.blank?)
        my_heritage_conditions << " AND (cultural_heritage_cultural_heritages.group = ?) "
        #my_heritage_values.push(@search_group)
        my_heritage_values.push(1)
    #end

    if (!@search_subgroup.blank?)
        my_heritage_conditions << " AND (cultural_heritage_cultural_heritages.subGroup = ?) "
        my_heritage_values.push(@search_subgroup)
    end
    my_heritage_values.insert(0, my_heritage_conditions)
    @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=> my_heritage_values)
    render :partial => "assing_table"
  end

  #Grabar asignaciones
  def save_assignments
    if (!user_signed_in? or !(@@edit_roles.include?(current_user.role)) )
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
      return
    end

    #Cuando un parámetro del request se nombra con corchetes se vuelve un arreglo
    #q contiene varios valores
    #Si este arreglo está vacío
    if params[:cultural_heritage_selected].blank?
      selecteds_ids = []
    else
      selecteds_ids=params[:cultural_heritage_selected]
    end

    #Selecciona la collection
    cultural_heritage_collection = CulturalHeritage::Collection.find(params[:collection_id])
    selected_cultural_heritages = []

    msg = "<br />La cantidad de objetos no puede exceder el tamaño original de la colección."
    #si he seleccionado más elementos de los permitidos
    if selecteds_ids.size <= cultural_heritage_collection.original_size

      #para cada id de los cultural_geritages haz un select y obtén el cultural_heritage correspondiente
      selecteds_ids.each do |selected_id|
        selected_cultural_heritages << CulturalHeritage::CulturalHeritage.find(selected_id)
      end

      #Obtén la lista antigua de cultural_heritage de la collection
      assignments_list = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["cultural_heritage_cultural_heritages.collection = ?",cultural_heritage_collection.id])

      #lista de nuevos cultural_heritage de la collection
      assignments_to_save_list = []
      #para cada patrimonio actualmente seleccionado actualiza el campo collection
      selected_cultural_heritages.each do |selected_cultural_heritage|
        selected_cultural_heritage.collection = cultural_heritage_collection.id
        assignments_to_save_list << selected_cultural_heritage
      end

      #para cada elmento de esa lista antigua verifica q no este en la nueva lista
      assignments_list.each do |old_assing|
        is_in = false
        selected_cultural_heritages.each do |selected_cultural_heritage|
          if (old_assing.id == selected_cultural_heritage.id)
            is_in = true
            break
          end
        end
        #Si no está en la nueva lista, actualiza el campo collection a nil, sin collection
        if (! is_in)
          old_assing.collection = nil
          assignments_to_save_list << old_assing
        end
      end
      no_problem = true
      #Ahora graba en la BD todos los cambios
      assignments_to_save_list.each do |assignment_to_save|
        s_cultural_heritage = CulturalHeritage::CulturalHeritage.find(assignment_to_save.id)
        if (s_cultural_heritage.collection.blank? or s_cultural_heritage.collection == cultural_heritage_collection.id )
          assignment_to_save.save
        else
          no_problem = false
        end
      end

      #Graba en la BD el tamaño actual
      cultural_heritage_collection.current_size = selecteds_ids.size

      if selecteds_ids.size < cultural_heritage_collection.original_size
        cultural_heritage_collection.state = 2
      elsif selecteds_ids.size == cultural_heritage_collection.original_size
        cultural_heritage_collection.state = 3
      end

      cultural_heritage_collection.save

    else
      #no puedo meter más objetos del tamaÑo
      no_problem = false
      msg = "\nLa cantidad de objetos no puede exceder el tamaño original de la colección."

    end #selecteds_ids.size <= cultural_heritage_collection.original_size
    
    if (no_problem)
      respond_to do |format|
        #format.html { redirect_to(:controller=>"/cultural_heritage/collections",:action => 'assing',:id =>cultural_heritage_collection.id, :notice => 'Asignacion exitosa.') }
        format.html { redirect_to(cultural_heritage_collection, :notice => 'La colección fue modificada satisfactoriamente.') }
        flash[:notice] = 'Asignacion exitosa.'
        format.xml  { head :ok }
      end
    else
      respond_to do |format|
        format.html { redirect_to(:controller=>"/cultural_heritage/collections",:action => 'assing',:id =>cultural_heritage_collection.id, :notice => 'Se han generado problemas asignando algunos elementos.')}
        flash[:notice] = 'Se han generado problemas asignando algunos elementos.' + msg
        #format.xml  { render :xml => @cultural_heritage_cultural_heritage.errors, :status => :unprocessable_entity }
      end
    end
  end
  #Fin de la asignación

  #galería de fotos
  def new_photo
    if (!user_signed_in? or !(@@edit_roles.include?(current_user.role)) )
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
      return
    end
    
    @title_view = 'Colecciones'
    @cultural_heritage_collection_photo = CulturalHeritage::CollectionPhoto.new()
    @cultural_heritage_collection = CulturalHeritage::Collection.find(params[:id])
    @cultural_heritage_collection_photo.collection = params[:id]

    respond_to do |format|
      format.html {render :layout => "blank_fullwidth"}# index.html.erb
      format.xml  { render :xml => @cultural_heritage_collection_photo }
    end
  end

  def create_photo
    if (!user_signed_in? or !(@@edit_roles.include?(current_user.role)) )
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
      return
    end

    @title_view = 'Colecciones'
    #@cultural_heritage_collection_photo = CulturalHeritage::CollectionPhoto.new(params[:cultural_heritage_collection_photo])
    @cultural_heritage_collection = CulturalHeritage::Collection.find(params[:id])
    #@cultural_heritage_collection_photo.collection = params[:id]

    @uploaded_io_array = params[:cultural_heritage_collection_photo][:photo]

#    @photo =
#        CulturalHeritage::CollectionPhoto.create([
#          :collection => 1,
#          :title => "uploaded_io.original_filename",
#          :description => "params[:description]",
#          :photo_file_name => "uploaded_io.original_filename",
#          :photo_content_type => "uploaded_io.content_type",
#          ])
#   # @photo.save

    @upload_ok = true;
    #@headers @tempfile


    @tit = params[:cultural_heritage_collection_photo][:title]
    @desc = params[:cultural_heritage_collection_photo][:description]

    if !@uploaded_io_array.nil?
      @uploaded_io_array.each do |uploaded_io|
        @cultural_heritage_collection_photo =
          CulturalHeritage::CollectionPhoto.create([
            :collection => @cultural_heritage_collection.id,
            :title => (@tit.blank? ? uploaded_io.original_filename.split('.')[0] : @tit),
            :description => @desc,
            :photo_file_name => uploaded_io.original_filename,
            :photo_content_type => uploaded_io.content_type,
            :photo => uploaded_io])

  #      if @cultural_heritage_collection_photo.save
  #        @upload_ok = @upload_ok
  #      else
  #        @upload_ok = false
  #      end
      end
    else
      @upload_ok = false;
    end

    #uploaded_io = params[:cultural_heritage_collection_photo][:photo]
#    File.open(Rails.root.join('public', 'system', 'photos', uploaded_io.original_filename), 'wb') do |file|
#      file.write(uploaded_io.read)
#    end
    respond_to do |format|
      if @upload_ok #@cultural_heritage_collection_photo.save
        @@my_notice = 'Las fotos fueron cargadas satisfactoriamente.'
        format.html { redirect_to(:controller=>"/cultural_heritage/collections", :action => 'new_photo',:id => @cultural_heritage_collection.id, :notice => 'Las fotos fueron cargadas satisfactoriamente.',:layout => "blank_fullwidth") }
        format.xml  { render :xml => @cultural_heritage_collection_photo, :status => :created, :location => @cultural_heritage_collection_photo }
        #
        #format.html { redirect_to(:controller=>"/cultural_heritage/collections", :action => 'show',:id => @cultural_heritage_collection.id, :notice => 'Las fotos fueron cargadas satisfactoriamente.',:layout => "blank_fullwidth") }
        #format.xml  { render :xml => @cultural_heritage_collection_photo, :status => :created, :location => @cultural_heritage_collection_photo }
      else
        @@my_notice = 'Hubo un problema en la carga de fotos.'
        format.html { redirect_to(:controller=>"/cultural_heritage/collections", :action => 'new_photo',:id => @cultural_heritage_collection.id, :notice => 'Hubo un problema en la carga de fotos.',:layout => "blank_fullwidth") }
        format.xml  { render :xml => @cultural_heritage_collection_photo.errors, :status => :unprocessable_entity }

        #format.html { render :action => "new_photo", :controller=>"/cultural_heritage/collections", :notice => 'Hubo un error en el proceso.',:layout => "blank_fullwidth"}
        #format.xml  { render :xml => @cultural_heritage_collection_photo.errors, :status => :unprocessable_entity }
      end
    end
  end

  

  def delete_photo
    if (!user_signed_in? or !(@@edit_roles.include?(current_user.role)) )
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
      return
    end
    
    @cultural_heritage_collection_photo = CulturalHeritage::CollectionPhoto.find(params[:id])

    #@collection_id = @cultural_heritage_collection_photo.collection
    @cultural_heritage_collection = CulturalHeritage::Collection.find(@cultural_heritage_collection_photo.collection)

    @cultural_heritage_collection_photo.deleted = 1
    @cultural_heritage_collection_photo.save
    respond_to do |format|
      format.html { redirect_to(@cultural_heritage_collection, :notice => 'La foto borrada satisfactoriamente.') }
      #format.html { redirect_to(:action => 'show',:id => @collection_id, :notice => 'Foto borrada.') }
      format.xml  { head :ok }
    end
  end

end
